package top.imyzt.controller;


import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.io.IOException;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author imyzt123
 * @since 2018-01-11
 */
@Api("文件上传工具类")
@RestController
@RequestMapping("/file")
public class FileController extends BaseController{

	private static final int imgSize = 5 * 1024 * 1024;

	/**
	 * 上传图片
	 */
	@ApiOperation("单文件上传")
	@RequestMapping(value="/single", method = RequestMethod.POST)
	public Object singleFileUpload(
			@RequestParam("file") MultipartFile file,
			HttpServletRequest req) throws IOException{

		if (file != null) {

			long fileSize = file.getSize();

			if(fileSize <= imgSize) {

				String filePath = req.getSession().getServletContext().getRealPath("upload");
				String uuid = UUID.randomUUID().toString().replace("-", "");
				String fileName = file.getOriginalFilename();
				String suffix = fileName.substring(fileName.indexOf('.') + 1);

				java.io.File saveFile = new java.io.File(filePath, uuid + "." + suffix);
				
				if (saveFile.createNewFile()) {
					
					//转存文件
					file.transferTo(saveFile);
				}
				
				/*
				 * 文件路径存储数据库操作
				 */

				return retContent(200, null);
			}else {
				return retContent(1201, null);
			}
		}
		return retContent(1202, null);
	}




	/**  
	 * 编码  
	 *   
	 * @param bstr  
	 * @return String  
	 */    
//	public static String encode(byte[] bstr) {    
//		return new sun.misc.BASE64Encoder().encode(bstr);    
//	}    

	/**  
	 * 解码  
	 *   
	 * @param str  
	 * @return string  
	 */    
//	public static byte[] decode(String str) {    
//		byte[] bt = null;    
//		try {    
//			sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();    
//			bt = decoder.decodeBuffer(str);    
//		} catch (IOException e) {    
//			e.printStackTrace();   
//		}
//		return bt; 
//	}
	
}

